package huge

import (
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc/status"
	"qm_system_server/server/global"
	"qm_system_server/server/model/common/response"
	"qm_system_server/server/model/system"
	"qm_system_server/server/proto/grpc/huge"
	"qm_system_server/server/service"
	"strconv"
)

type QmAccessTokensApi struct {
}

var qmAccessTokensService = service.ServiceGroupApp.HugeServiceGroup.QmAccessTokensService

// CreateQmAccessTokens 创建qmAccessTokens表
// @Tags QmAccessTokens
// @Summary 创建qmAccessTokens表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body huge.QmAccessTokens true "创建qmAccessTokens表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /qmAccessTokens/createQmAccessTokens [post]
func (qmAccessTokensApi *QmAccessTokensApi) CreateQmAccessTokens(c *gin.Context) {
	type Request struct {
		UserId     int64  `json:"userId" form:"userId"`
		AppId      string `json:"appId" form:"appId"`
		Secret     string `json:"secret" form:"secret"`
		Platform   string `json:"platform" form:"platform"`
		PlatformId string `json:"platformId" form:"platformId"`
	}

	var req Request
	_ = c.ShouldBind(&req)

	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	client := huge.NewHugeServiceClient(global.OperateGrpc)

	resp, err := client.Create(context.Background(), &huge.CreateRequest{
		UserId:     int64(req.UserId),
		AppId:      req.AppId,
		Secret:     req.Secret,
		Platform:   req.Platform,
		PlatformId: req.PlatformId,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(resp.AppId, c)
}

// UpdateQmAccessTokens 更新qmAccessTokens表
// @Tags QmAccessTokens
// @Summary 更新qmAccessTokens表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body huge.QmAccessTokens true "更新qmAccessTokens表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /qmAccessTokens/updateQmAccessTokens [put]
func (qmAccessTokensApi *QmAccessTokensApi) UpdateQmAccessTokens(c *gin.Context) {
	type Request struct {
		UserId            int64  `json:"userId" form:"userId"`
		AccessToken       string `json:"accessToken" form:"accessToken"`
		ExpireTime        int64  `json:"expireTime" form:"expireTime"`
		RefreshToken      string `json:"refreshToken" form:"refreshToken"`
		RefreshExpireTime int64  `json:"refreshExpireTime" form:"refreshExpireTime"`
	}

	var req Request
	_ = c.ShouldBind(&req)

	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.Update(context.Background(), &huge.UpdateRequest{
		UserId:            int64(req.UserId),
		AccessToken:       req.AccessToken,
		ExpireTime:        req.ExpireTime,
		RefreshToken:      req.RefreshToken,
		RefreshExpireTime: req.RefreshExpireTime,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(resp.UserId, c)
}

// FindQmAccessTokens 用id查询qmAccessTokens表
// @Tags QmAccessTokens
// @Summary 用id查询qmAccessTokens表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query huge.QmAccessTokens true "用id查询qmAccessTokens表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /qmAccessTokens/findQmAccessTokens [get]
func (qmAccessTokensApi *QmAccessTokensApi) FindQmAccessTokens(c *gin.Context) {
	type Request struct {
		UserId     int64  `form:"userId" json:"userId"`
		PlatformId string `form:"platformId" json:"platformId"`
	}

	var req Request
	_ = c.ShouldBind(&req)
	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.Get(context.Background(), &huge.GetRequest{
		UserId:     req.UserId,
		PlatformId: req.PlatformId,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(resp, c)
}

func (qmAccessTokensApi *QmAccessTokensApi) GetInfo(c *gin.Context) {
	type Request struct {
		UserId int64  `form:"userId" json:"userId"`
		Type   string `form:"type" json:"type"`
		Params string `form:"params" json:"params"`
	}

	var req Request
	_ = c.ShouldBind(&req)

	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.GetInfo(context.Background(), &huge.InfoRequest{
		UserId: req.UserId,
		Type:   req.Type,
		Params: req.Params,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	if resp.Info == "0" {
		response.FailWithMessage(resp.Message, c)
	} else {
		response.OkWithData(resp, c)
	}
}

func (qmAccessTokensApi *QmAccessTokensApi) GetUserPlatform(c *gin.Context) {
	type Request struct {
		UserId int64 `form:"userId" json:"userId"`
	}

	var req Request
	_ = c.ShouldBind(&req)

	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	var gameList []system.SysUserGame
	global.GVA_DB.Where("sys_user_id = ?", req.UserId).Find(&gameList)

	var gameIds string
	for _, game := range gameList {
		str := strconv.FormatUint(uint64(game.QmGameId), 10)
		gameIds += str + ","
	}

	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.GetUserPlatform(context.Background(), &huge.GetUserPlatformRequest{
		Ids: gameIds,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(resp.Response, c)
}

func (qmAccessTokensApi *QmAccessTokensApi) GetAccountData(c *gin.Context) {
	type Request struct {
		UserId     int64  `form:"user_id" json:"user_id"`
		PlatformId string `form:"platform" json:"platform"`
		Date       string `form:"date" json:"date"`
		Page       string `form:"page" json:"page"`
		PageSize   string `form:"page_size" json:"page_size"`
		Keyword    string `form:"keyword" json:"keyword"`
		GameId     string `form:"game_id" json:"game_id"`
	}

	var req Request
	_ = c.ShouldBind(&req)

	xUserid := c.Request.Header.Get("X-User-Id")
	req.UserId, _ = strconv.ParseInt(xUserid, 10, 64)

	client := huge.NewHugeServiceClient(global.OperateGrpc)

	var userGame string
	var userGameList []system.SysUserGame
	global.GVA_DB.Where("sys_user_id = ?", req.UserId).Find(&userGameList)
	for _, game := range userGameList {
		userGame += strconv.FormatUint(uint64(game.QmGameId), 10) + ","
	}
	resp, err := client.GetDataInfo(context.Background(), &huge.DataRequest{
		UserId:     req.UserId,
		PlatformId: req.PlatformId,
		Date:       req.Date,
		Page:       req.Page,
		UserGame:   userGame,
		Keyword:    req.Keyword,
		PageSize:   req.PageSize,
		GameHash:   req.GameId,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}
	response.OkWithData(resp, c)
}
